package fi.aalto.cse.T110_5150.P2PClient;

import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class P2PHelper {

	public static final byte VERSION_CURRENT = 1;

	/* Default listening port */
	public static final int PORT_DEFAULT = 8601;

	/* definition of protocol message type */
	public static final int MESSAGE_TYPE_PING = 0x00;
	public static final int MESSAGE_TYPE_PONG = 0x01;
	public static final int MESSAGE_TYPE_BYE = 0x02;
	public static final int MESSAGE_TYPE_JOIN = 0x03;
	public static final int MESSAGE_TYPE_QUERY = 0x80;
	public static final int MESSAGE_TYPE_QUERY_HIT = 0x81;

	/* Network error codes */
	public static final int STATUS_OK = 0x0200;

	/* Ping-pong parameters */
	public static final long PING_PONG_HEART_BEAT_INTERVAL = 5000;
	public static final int PING_PONG_HEART_BEAT_TTL = 1;

	public static final long PING_PONG_NETWORK_PROBING_INTERVAL = 60000;
	public static final int PING_PONG_NETWORK_PROBING_TTL = 2;
	public static final int PING_PONG_NETWORK_PROBING_MAX_PEER = 5;

	/* Socket properties */	
	public static final int SOCKET_INPUT_TIMEOUT = 60000;
	
	/* Query and QueryHit */
	public static final int  QUERY_MAX_TTL = 5;
	public static final long QUERY_VALIDITY_PERIOD = 120000;
	
	/* Logger */
	
	public static final int LOGGER_ENABLE_DEGUG = Logger.NONE;

	/**
	 * private static fields
	 */
	private static final Random randomizer = new Random();

	private static MessageDigest messageDigest;

	public static int nextRandom(int max) {
		return randomizer.nextInt(max);
	}

	/**
	 * Gets the hash value for a string
	 * 
	 * @param s
	 * @return
	 */
	public static int getHashValue(String s) {
		if (messageDigest == null) {
			try {
				messageDigest = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException e) {
			}
		}
		byte[] bytes = messageDigest.digest(s.getBytes());
		return ByteBuffer.wrap(bytes).getInt();
	}
}
